package com.ebupt.migu.music.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Created by Intellij IDEA.
 * User:  liuyangyang@cd.ebupt.com
 * Date:  2019/10/23
 */
@Slf4j
public class HttpUtils {

    private static final int MAX_TIMEOUT = 10000;
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    // 线程安全的
    private static CloseableHttpClient httpClient;

    static {
        // 设置连接池
        connMgr = new PoolingHttpClientConnectionManager();
        connMgr.setMaxTotal(500);
        connMgr.setDefaultMaxPerRoute(10);
//        HttpHost host = new HttpHost("10.25.204.31", 9999, "http");
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置链接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
//        configBuilder.setProxy(host);
        requestConfig = configBuilder.build();
        httpClient = HttpClients.custom().setConnectionManager(connMgr).build();
    }

    /*** 发送 POST 请求（HTTP），K-V形式**
     * @param apiUrl*            API接口URL*
     * @param params*            参数map*
     * @param headerParams*      header map*
     * @return
     * */
    public static String doPost(String apiUrl, Map<String, Object> params, Map<String, String> headerParams) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connMgr)
                .setDefaultRequestConfig(requestConfig).build();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        try {
            httpPost.setConfig(requestConfig);
            if (null == params || params.isEmpty()) {
                log.info("params is empty");
            }

            String json = JsonUtils.obj2Json(params);
            log.info("请求报文:{}", json);
            StringEntity entitys = new StringEntity(json, "UTF-8");
            entitys.setContentType("application/json");

            httpPost.setEntity(entitys);
            if (headerParams.size() > 0) {
                Set<Entry<String, String>> set = headerParams.entrySet();
                for (Entry<String, String> entry : set) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            response = httpClient.execute(httpPost);
            if (null == response) {
                throw new RuntimeException("response对象为空");
            }
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
            if (null != response) {
                EntityUtils.consume(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeResponse(response);
        }
        log.info("响应报文:{}", httpStr);
        return httpStr;
    }

    private static void closeResponse(CloseableHttpResponse response) {
        if (response != null) {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
